<?php
include("../config/config.php");

try {
	$db = Outils_Bd::getInstance()->getConnexion();
	
	$requeteTruncate = "TRUNCATE TABLE Popularity";
	$db->exec($requeteTruncate);
	
	$requeteMAJ = "SELECT id_title, ((SUM(score-5)*". POP_PONDERATION_SCORE ." )+ (COUNT(*)*". POP_PONDERATION_NBEVAL .") - (TIMESTAMPDIFF(DAY,time,NOW())*". POP_PONDERATION_TIME .")) as popularity FROM Rating WHERE score>0 GROUP BY id_title  ORDER BY popularity DESC LIMIT 1000";
	$sth = $db->query($requeteMAJ);
	$resultats = $sth->fetchAll(PDO::FETCH_ASSOC);
	
	foreach($resultats as $resultat){  
		$requete = "INSERT INTO Popularity SET id_title=:id_title, popularity=:popularity";
		$sth=$db->prepare($requete);
		$data=array(
			'popularity' => $resultat['popularity'],
			'id_title' => $resultat['id_title']
		); 
		 $sth->execute($data);
	}

} catch (Exception $e) {
	echo $e->getMessage();
	echo "<pre>{$e->getTraceAsString()}</pre>";
}


?>